package com.vfa.fishing;

import java.util.Random;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.audio.sound.Sound;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.camera.hud.controls.DigitalOnScreenControl;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.modifier.RotationModifier;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.entity.text.Text;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.texture.BuildableTexture;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.builder.BlackPawnTextureBuilder;
import org.anddev.andengine.opengl.texture.builder.ITextureBuilder.TextureSourcePackingException;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.HorizontalAlign;

import com.vfa.fishing.common.Constant;
import com.vfa.fishing.object.AbstractObject;
import com.vfa.fishing.object.Fish;
import com.vfa.fishing.object.Person;

import android.graphics.Color;
import android.util.DisplayMetrics;
import android.util.Log;

public class GameActivity extends BaseGameActivity implements IOnSceneTouchListener//,IAccelerometerListener
{
     // ===========================================================
    // Constants
    // ===========================================================

//    private static final int CAMERA_WIDTH = CELLS_HORIZONTAL * CELL_WIDTH; // 640
//    private static final int CAMERA_HEIGHT = CELLS_VERTICAL * CELL_HEIGHT; // 480




    private static final int LAYER_BACKGROUND = 0;
    private static final int LAYER_FOOD = LAYER_BACKGROUND + 1;
    private static final int LAYER_SNAKE = LAYER_FOOD + 1;
//    private static final int LAYER_SCORE = LAYER_SNAKE + 1;

    // ===========================================================
    // Fields
    // ===========================================================

    private Camera mCamera;

    private DigitalOnScreenControl mDigitalOnScreenControl;

    private Texture mFontTexture;
    private Font mFont;

    private Texture mBoatTexture;

    private Texture mBackgroundTexture;
    private TextureRegion mBackgroundTextureRegion;
    private TextureRegion arrTextureRegion [];
    private TiledTextureRegion arrFishImg [];
    private TiledTextureRegion boatTextureRegion;
    private Texture arrTexture [];


    private Texture mOnScreenControlTexture;
    private TextureRegion mOnScreenControlBaseTextureRegion;
    private TextureRegion mOnScreenControlKnobTextureRegion;
    private Fish fish;
//    private Frog mFrog;

    private int mScore = 0;
    private ChangeableText mScoreText;

    private Sound mGameOverSound;
    private Sound mMunchSound;
    protected boolean mGameRunning;
    private Text mGameOverText;
    public static Random rand;
    public Fish arrFish [];
    public final  int  numFish = 5;
    public Scene mySceme;
    public static int TIMER = 0;
    public int waterLine;
    public int fishKind;
    public int sideAppear;
    private BuildableTexture mBuildableTexture;
    public static int NUMOFFISH = 8;
    public AnimatedSprite face;
    // danh sach chua tat ca cac doi tuong trong game,dung danh sach nay de check va cham voi cac doi tuong khac
    public AbstractObject arrObject [];

    //declare boat sprite
    Sprite boatSprite;
    //Start:Boat position
    private int boatX=0;
    private int boatY=100;
    //End:Boat position
    //declare Person object
    Person boat;
    private int Xtarget;
    private boolean isTouch = false;


    @Override
    public Engine onLoadEngine() {

        this.mCamera = new Camera(0, 0, 800, 480);
        return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(MainActivity.CAMERA_WIDTH, MainActivity.CAMERA_HEIGHT), this.mCamera).setNeedsSound(true));
    }

    @Override
    public void onLoadResources() {
        rand = new Random();
        rand.setSeed(System.currentTimeMillis());
        Xtarget = 400;
        arrTexture = new Texture[NUMOFFISH];
        arrTextureRegion = new TextureRegion[NUMOFFISH];
        arrObject  = new AbstractObject[15];
        this.mBuildableTexture = new BuildableTexture(256, 256, TextureOptions.DEFAULT);

        arrFishImg = new TiledTextureRegion[NUMOFFISH];

        /* Load the font we are going to use. */
        waterLine = 200;
        arrFish = new Fish[numFish];
        FontFactory.setAssetBasePath("font/");
        this.mFontTexture = new Texture(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.mFont = FontFactory.createFromAsset(this.mFontTexture, this, "Plok.ttf", 32, true, Color.WHITE);

        this.mEngine.getTextureManager().loadTexture(this.mFontTexture);
        this.mEngine.getFontManager().loadFont(this.mFont);

        TextureRegionFactory.setAssetBasePath("gfx/");
        //Start:Boat texture
        this.mBoatTexture = new Texture(128, 128, TextureOptions.REPEATING_BILINEAR);
        this.boatTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mBoatTexture, this, "boat.png", 0, 0,1,1);
        //End:Boat texture

        for(int i=0;i<NUMOFFISH;i++) {
            arrTexture[i] = new Texture(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
            arrFishImg[i] = TextureRegionFactory.createTiledFromAsset(arrTexture[i], this,"fish"+i+".png",0,0,1,1);// hohoho
        }
        for(int i=0;i<NUMOFFISH;i++) {
            arrTextureRegion[i] = TextureRegionFactory.createFromAsset(arrTexture[i], this, "fish"+i+".png",0,0);
        }

        this.mBackgroundTexture = new Texture(1024, 512, TextureOptions.DEFAULT);
        this.mBackgroundTextureRegion = TextureRegionFactory.createFromAsset(this.mBackgroundTexture, this,"background1.png", 0, 0);

        this.mOnScreenControlTexture = new Texture(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.mOnScreenControlBaseTextureRegion = TextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0);
        this.mOnScreenControlKnobTextureRegion = TextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0);

        this.mEngine.getTextureManager().loadTextures(this.mBackgroundTexture, this.mOnScreenControlTexture);
        this.mEngine.getTextureManager().loadTextures(arrTexture);
        this.mEngine.getTextureManager().loadTextures(mBoatTexture);
    }

    @Override
    public Scene onLoadScene() {
        this.mEngine.registerUpdateHandler(new FPSLogger());

        final Scene scene = new Scene(3);
        /* No background color needed as we have a fullscreen background sprite. */
        scene.setBackgroundEnabled(false);
        scene.getChild(LAYER_BACKGROUND).attachChild(new Sprite(0, 0, this.mBackgroundTextureRegion));

        /* The ScoreText showing how many points the pEntity scored. */
        this.mScoreText = new ChangeableText(5, 5, this.mFont, "Score: 0", "Score: XXXX".length());
        this.mScoreText.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
        this.mScoreText.setAlpha(0.5f);
        scene.getChild(LAYER_SNAKE).attachChild(this.mScoreText);
        if(boat==null)
            boat = new Person(0, boatY, boatTextureRegion, 0);

        for(int i =0;i<arrFish.length;i++){
            int y = rand.nextInt(230)+150;// tao so ngau nhien tu 250--->480
            int x = -1;
            fishKind = GameActivity.rand.nextInt(8);
            sideAppear = rand.nextInt(2);
            if(sideAppear == Constant.LEFT){
                 x = -30;
            }
            else if(sideAppear == Constant.RIGHT){
                x = MainActivity.CAMERA_WIDTH+20;
            }
            arrFish[i] = new Fish(x ,y,  arrFishImg[i],sideAppear,fishKind);

            scene.getLastChild().attachChild(arrFish[i]);
        }
        //Start:Add boat sprite
//        boatSprite = new Sprite(boatX, boatY, this.boatTextureRegion);
        scene.getLastChild().attachChild(boat);
        scene.setOnSceneTouchListener(this);
        //End:Add boat sprite
        Log.e("LocNNT", "scene.getChild(LAYER_SNAKE).attachChild(this.fish);");

        /* Make the Snake move every 0.5 seconds. */
        scene.registerUpdateHandler(new TimerHandler(0.1f, true, new ITimerCallback() {
            @Override
            public void onTimePassed(final TimerHandler pTimerHandler) {
                TIMER++;
                 if(TIMER>1000000) {
                     TIMER = 0;
                 }
                update();
//                Log.e("LocNNT","timer dang dem la :   ======================="+  TIMER);
            }
        }));

        /* The title-text. */
        final Text titleText = new Text(0, 0, this.mFont, "Snake\non a Phone!", HorizontalAlign.CENTER);
        scene.registerUpdateHandler(new TimerHandler(3.0f, new ITimerCallback() {
            @Override
            public void onTimePassed(final TimerHandler pTimerHandler) {
                scene.unregisterUpdateHandler(pTimerHandler);
                scene.getChild(LAYER_SNAKE).detachChild(titleText);
            }
        }));

        /* The game-over text. */
        this.mGameOverText = new Text(0, 0, this.mFont, "Game\nOver", HorizontalAlign.CENTER);
        this.mGameOverText.registerEntityModifier(new ScaleModifier(3, 0.1f, 2.0f));
        this.mGameOverText.registerEntityModifier(new RotationModifier(3, 0, 720));
        mySceme = scene;
        return scene;
    }

    @Override
    public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent)
    {
        if(pSceneTouchEvent.isActionDown())
        {
                //update new position
//    			if(pSceneTouchEvent.getX()>0 && pSceneTouchEvent.getX() < MainActivity.CAMERA_WIDTH )
//    				boat.update(boatSprite,pSceneTouchEvent.getX(), boatY);
            Xtarget = (int) pSceneTouchEvent.getX();
            isTouch = true;
                return true;
        }
        return false;
    }

    @Override
    public void onLoadComplete() {

    }

    public void onGameOver() {
        this.mGameOverSound.play();
        this.mEngine.getScene().getChild(LAYER_SNAKE).attachChild(this.mGameOverText);
        this.mGameRunning = false;
    }

    public void update(){
    	// check va cham
    	checkColitionAllObject();
        // update nguoi cau ca
        if(boat!= null && isTouch)
        {
            boat.update(Xtarget);
//    		isTouch = false;
        }

        // update bay ca
        for(int i =0;i<arrFish.length;i++) {
             if(arrFish[i]!= null&& arrFish[i].checkCollision()){
                 int y = rand.nextInt(230)+150;// tao so ngau nhien tu 250--->480
                 int x = -1;
                 mySceme.getLastChild().detachChild(arrFish[i]);
                 arrFish[i] = null;
                 int sideApp = rand.nextInt(2);
                 if(sideApp == Constant.LEFT){
                      x = -30;
                 }
                 else if(sideApp == Constant.RIGHT){
                     x = MainActivity.CAMERA_WIDTH+20;
                 }
                 fishKind = GameActivity.rand.nextInt(8);
                 arrFish[i] = new Fish(x ,y, arrFishImg[i],sideApp,fishKind);
                 for(int j=0;j<arrObject.length;j++){
                	 if(arrObject[j]==null){
                		 arrObject[j]=arrFish[i];
                		 break;
                	 }
                 }
                 mySceme.getLastChild().attachChild(arrFish[i]);
             }
             else if(arrFish[i]!= null&& !arrFish[i].checkCollision()){
            	 arrFish[i].update();
             }
        }
        //update bay tom
        //update bay muc
    }
    private void checkColitionAllObject(){
    	// duyen qua danh sach,check va cham cua 1 doi tuong voi nhung doi tuong khac
    	for(int i=0;i<arrObject.length;i++){
//    		Log.e("LocNNT", "gia tri cua i la :  "+i);
    		if(arrObject[i]!= null){
    			AbstractObject obj = arrObject[i];
    			for(int j = i+1;j<arrObject.length;j++){
//    				Log.e("LocNNT", "gia tri cua j la :  "+j);
    				if(arrObject[j]!= null){
    					if(obj.checkCollision(arrObject[j])){
    						// check xem co phai ca ko ,neu dung thi co con nao an duoc nhau ko,
    						if(arrObject[j].kindOfObject == Constant.FISH && obj.kindOfObject == Constant.FISH){
    							Fish fish = (Fish)arrObject[j];
    							if(fish.iTerrible == 0){// ca hung du thi iterible =0
    								mySceme.getLastChild().detachChild(obj);
    								obj = null;
    								break;
    							}
    						}
    						arrObject[j].resetDirection();
    						if(obj!= null)
    							obj.resetDirection();
    					}
    				}
    			}
    			
    		}
    	}
    	
    }

}